﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Configuration;
using System.IO;
using FisheryPlatform.Common.StaticCache;
using FisheryPlatform.Bussiness.LoginCookie;
using FisheryPlatform.SiteConfig;
using FisheryPlatform.Bussiness.Post;
using FisheryPlatform.SiteConfig.FileStore;
using FisheryPlatform.Bussiness.FileStore;

namespace FisheryPlatform.Bussiness.Cache
{
    public class PostStaticHtmlCache
    {
        public static string GetFileName(string postId, DateTime postDate)
        {
            var uploadFile = new UploadFileEntity(postId, PostStaticHtmlUploadProvider.defaultExtensionName, new byte[] { });
            uploadFile.UploadDate = postDate;
            PostStaticHtmlUploadProvider productUpload = new PostStaticHtmlUploadProvider(uploadFile);
            return uploadFile.PublishUrl + uploadFile.PublishUrlPath;
        }

        /// <summary>
        /// 获取缓存文件
        /// </summary>
        /// <param name="publishUrlPath"></param>
        /// <returns></returns>
        public static string Get(string publishUrlPath)
        {
            #region
            var text = PostStaticHtmlUploadProvider.GetFileContent(publishUrlPath);
            if (string.IsNullOrEmpty(text))
            {
                var id = Path.GetFileNameWithoutExtension(publishUrlPath);
                text = GetHtmlContext(id);
                if (!string.IsNullOrEmpty(text))
                {
                    var postInfo = PostManager.GetByPostId(long.Parse(id));
                    var uploadFile = new UploadFileEntity(id, PostStaticHtmlUploadProvider.defaultExtensionName, Encoding.Default.GetBytes(text));
                    uploadFile.UploadDate = postInfo.Post.PostDate;
                    PostStaticHtmlUploadProvider productUpload = new PostStaticHtmlUploadProvider(uploadFile);
                    productUpload.Save();
                }
            }
            return text;
            #endregion
        }

        public static string GetHtmlContext(string postId)
        {
            #region
            var resposeText = "";
            try
            {
                var url = (SiteConfigManager.AppSettings["GenerateStaticHtmlUrl.Post"].Value ?? SiteConfigManager.WebSite.WWW + "/Post/Details.aspx?postid=") + postId;
                //request
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.UserAgent = "LaoZhouYuYe--Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)";
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                request.KeepAlive = true;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();

                if (responseStream != null)
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    resposeText = reader.ReadToEnd();
                }
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    resposeText = "";
                }
                response.Close();
            }
            catch (Exception e)
            {
                Exception ex = new Exception(e.ToString());
                ExceptionMessage.Record(ex);
            }
            return resposeText;
            #endregion
        }

        /// <summary>
        /// 删除缓存文件
        /// </summary>
        /// <param name="fileName"></param>
        public static void Delete(long postId)
        {
            var postInfo = PostManager.GetByPostId(postId);

            UploadFileEntity uploadFile = new UploadFileEntity(postInfo.Post.PostId.ToString(), PostStaticHtmlUploadProvider.defaultExtensionName, new byte[] { });
            uploadFile.UploadDate = postInfo.Post.PostDate;//必须得
            PostStaticHtmlUploadProvider fileUploadProvider = new PostStaticHtmlUploadProvider(uploadFile);
            fileUploadProvider.Delete();
        }
    }
}
